package org.dousb.doupicturebackend.manager.websocket;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import groovyjarjarantlr4.v4.runtime.misc.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.dousb.doupicturebackend.manager.auth.SpaceUserAuthManager;
import org.dousb.doupicturebackend.manager.auth.model.SpaceUserPermissionConstant;
import org.dousb.doupicturebackend.model.entity.Picture;
import org.dousb.doupicturebackend.model.entity.Space;
import org.dousb.doupicturebackend.model.entity.User;
import org.dousb.doupicturebackend.model.enums.SpaceTypeEnum;
import org.dousb.doupicturebackend.service.PictureService;
import org.dousb.doupicturebackend.service.SpaceService;
import org.dousb.doupicturebackend.service.UserService;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


/**
 * websocket拦截器
 * 拦截权限 和 空值
 */
@Component
@Slf4j
public class WSHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * WebSocket握手前的拦截方法，用于验证用户权限和请求参数
     *
     * @param request    服务器HTTP请求对象
     * @param response   服务器HTTP响应对象
     * @param wsHandler  WebSocket处理器
     * @param attributes WebSocket会话属性集合
     * @return 是否允许握手建立连接
     * @throws Exception 可能抛出的异常
     */
    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, @NotNull Map<String, Object> attributes) throws Exception {
        // 判断请求是否为Servlet类型的HTTP请求
        if (request instanceof ServletServerHttpRequest) {
            // 将请求转换为ServletServerHttpRequest以获取HttpServletRequest
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            //获取请求参数中的图片ID
            String pictureId = servletRequest.getParameter("pictureId");
            // 检查图片ID是否为空
            if (StrUtil.isBlank(pictureId)) {
                log.error("缺少图片参数，拒绝握手");
                return false;
            }
            // 获取当前登录用户信息
            User loginUser = userService.getLoginUser(servletRequest);
            // 检查用户是否已登录
            if (ObjUtil.isEmpty(loginUser)) {
                log.error("用户未登录，拒绝握手");
                return false;
            }
            // 校验用户是否有该图片的权限
            Picture picture = pictureService.getById(pictureId);
            if (picture == null) {
                log.error("图片不存在，拒绝握手");
                return false;
            }
            Long spaceId = picture.getSpaceId();
            Space space = null;
            if (spaceId != null) {
                space = spaceService.getById(spaceId);
                if (ObjUtil.isEmpty(space)) {
                    log.error("空间不存在，拒绝握手");
                    return false;
                }
                if (space.getSpaceType() != SpaceTypeEnum.TEAM.getValue()) {
                    log.info("不是团队空间，拒绝握手");
                    return false;
                }
            }

            List<String> permissionsList = spaceUserAuthManager.getPermissionsList(space, loginUser);
            if (!permissionsList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)) {
                log.error("没有编辑权限,拒绝握手");
                return false;
            }
            //设置attributes
            attributes.put("user", loginUser);
            attributes.put("userId", loginUser.getId());
            attributes.put("spaceId", spaceId);
            attributes.put("pictureId", Long.valueOf(pictureId));
        }
        return true;
    }


    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}